//
//  AddressBookController.m
//  LLKContacterDemo
//
//  Created by RongZhou on 17/2/9.
//  Copyright © 2017年 RongZhou. All rights reserved.
//

#import "AddressBookController.h"
#import "PPGetAddressBook.h"
#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>
#import "SelectAlert.h"
#import "ContacterCell.h"
#import "DialDetailInformationViewController.h"
#import <AFNetworking.h>
#define kScreenWidth        [UIScreen mainScreen].bounds.size.width
#define kScreenHeight       [UIScreen mainScreen].bounds.size.height
#define START NSDate *startTime = [NSDate date]
#define END NSLog(@"Time: %f", -[startTime timeIntervalSinceNow])

@interface AddressBookController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate,UISearchControllerDelegate,ABNewPersonViewControllerDelegate>

@property (nonatomic, assign) BOOL isBeginSearch;
@property(nonatomic,assign)BOOL isSearch;
@property (nonatomic, copy) NSDictionary *contactPeopleDict;
@property (nonatomic, copy) NSArray *keys;

@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)UISearchBar *searchBar;
@property(nonatomic,strong)NSMutableArray *matchFriendList;
@property(nonatomic,strong)NSMutableArray *keysArray;
@property(nonatomic,strong)NSMutableArray  *modelArra;
@property(nonatomic,copy)NSString *phoneNumberArea;
@end

@implementation AddressBookController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initUI];
    [self getContacterPeopleInformation];
}
-(void)initUI{
    UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addNewPerson)];
    self.navigationItem.rightBarButtonItem = rightBtn;
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"联系人";
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 64, kScreenWidth, 44)];
    self.searchBar.placeholder = @"搜索";
    self.searchBar.delegate = self;
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 44, kScreenWidth, kScreenHeight-44)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    UINib *nib = [UINib nibWithNibName:@"ContacterCell" bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:@"ContacterCell"];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.searchBar];
     self.tableView.tableFooterView = [UIView new];
}
-(void)addNewPerson{
    ABNewPersonViewController *picker = [[ABNewPersonViewController alloc] init];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:picker];
    picker.newPersonViewDelegate = self;
    [self presentViewController:nav animated:YES completion:^{
        
    }];
}
-(void)newPersonViewController:(ABNewPersonViewController *)newPersonView didCompleteWithNewPerson:(ABRecordRef)person{
    [self dismissViewControllerAnimated:YES completion:nil];
    [self getContacterPeopleInformation];
}

-(void)getContacterPeopleInformation{

    UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    indicator.frame = CGRectMake(0, 0, 80, 80);
    indicator.center = CGPointMake([UIScreen mainScreen].bounds.size.width*0.5, [UIScreen mainScreen].bounds.size.height*0.5-80);
    indicator.backgroundColor = [UIColor colorWithWhite:0.000 alpha:0.700];
    indicator.clipsToBounds = YES;
    indicator.layer.cornerRadius = 6;
    [indicator startAnimating];
    [self.view addSubview:indicator];
    //获取按联系人姓名首字拼音A~Z排序(已经对姓名的第二个字做了处理)
    [PPGetAddressBook getOrderAddressBook:^(NSDictionary<NSString *,NSArray *> *addressBookDict, NSArray *nameKeys) {
        [indicator stopAnimating];
        //装着所有联系人的字典
        self.contactPeopleDict = addressBookDict;
        NSLog(@"%@",self.contactPeopleDict);
        //联系人分组按拼音分组的Key值
        self.keys = nameKeys;
        [self.tableView reloadData];
    } authorizationFailure:^{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
        message:@"请在iPhone的“设置-隐私-通讯录”选项中，允许诚信宝访问您的通讯录"
        delegate:nil cancelButtonTitle:@"知道了"otherButtonTitles:nil];
        [alert show];
    }];
    self.tableView.rowHeight = 60;
}
#pragma mark -tableview的代理方法
#pragma mark - TableViewDatasouce/TableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (_isSearch) {
        return 1;
    }else{
        return _keys.count;
    }
   
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_isSearch) {
        return self.matchFriendList.count;
    }else{
        NSString *key = _keys[section];
        return [_contactPeopleDict[key] count];

    }
}

- (NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (_isSearch) {
        return nil;
    }else{
      return _keys[section];
    }
    
}

//右侧的索引
- (NSArray*)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    if (_isSearch) {
        return nil;
    }else{
      return _keys;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ContacterCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ContacterCell"];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    if (_isSearch) {
        PPPersonModel *people = self.matchFriendList[indexPath.row];
        cell.model = people;
    }else{
    NSString *key = _keys[indexPath.section];
    PPPersonModel *people = [_contactPeopleDict[key] objectAtIndex:indexPath.row];
        cell.model = people;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *key = _keys[indexPath.section];
    PPPersonModel *people = [_contactPeopleDict[key] objectAtIndex:indexPath.row];
    if (people.mobileArray.count == 1) {
        NSString *phoneNumber = people.mobileArray[0];
        [ self checkPhoneNumberArea:phoneNumber And:people];
    }else{
        [SelectAlert showWithTitle:@"选择手机号码" titles:people.mobileArray selectIndex:^(NSInteger selectIndex) {
            
        } selectValue:^(NSString *selectValue) {
            [self checkPhoneNumberArea:selectValue And:people];
        } showCloseButton:NO];
    }

}
/**
 *  获取手机号信息
 *
 *  @param phoneNumber <#phoneNumber description#>
 */
-(void)checkPhoneNumberArea:(NSString *)phoneNumber And:(PPPersonModel *)people{
    DialDetailInformationViewController *vc = [[DialDetailInformationViewController alloc] init];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *str = ServiceUrl@"/phoneAreaApp/searchCustomerByPhone?phone=%@";
    NSString *url = [NSString stringWithFormat:str,phoneNumber];
    [manager GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        if (dict[@"area"] == nil) {
            vc.phoneNumberArea = @"";
        }else{
            vc.phoneNumberArea = dict[@"area"];
        }
        vc.phoneNumber = phoneNumber;
        vc.userName = people.name;
        [self.navigationController pushViewController:vc animated:YES];
        NSLog(@"我是当前线程%@",[NSThread currentThread]);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

#pragma mark-搜索的代理方法
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    [self.matchFriendList removeAllObjects];
    [self.keysArray removeAllObjects];
    if (searchText.length <= 0) {
        _isSearch = NO;
        [self getContacterPeopleInformation];
    }else{
        _isSearch = YES;
        NSArray *arra = [self.contactPeopleDict allValues];
        NSArray *array = [self backModelFromArray:arra];
        NSLog(@"123=%@",array);
        for (PPPersonModel *model in array) {
            if ([model.name rangeOfString:searchText options:NSCaseInsensitiveSearch].location != NSNotFound) {
                [self.matchFriendList addObject:model];
                
            }
        }
        NSLog(@"333=%@",self.matchFriendList);
        [self.tableView reloadData];
    }
}

/**
 *  数组转化生成model类型数组
 *
 *  @param array
 *
 *  @return
 */
-(NSArray *)backModelFromArray:(NSArray *)array{
    NSMutableArray *backArray = [NSMutableArray array];
    for (int i = 0; i < array.count; i++) {
        NSArray *arra = array[i];
        for (PPPersonModel *model in arra) {
            [backArray addObject:model];
        }
    }
    return backArray;
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    _searchBar.frame = CGRectMake(0, 64, self.view.frame.size.width, 44);
    self.navigationController.navigationBarHidden = NO;
    _searchBar.showsCancelButton = NO;
    [_searchBar resignFirstResponder];
    _searchBar.text = @"";
    _isSearch = NO;
    [self.tableView reloadData];
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    [UIView animateWithDuration:0.3 animations:^{
        self.navigationController.navigationBarHidden = YES;
        _searchBar.frame = CGRectMake(0, 20, self.view.frame.size.width, 44);
        _searchBar.showsCancelButton = YES;
    }];
}

#pragma mark -数据懒加载
-(NSMutableArray *)matchFriendList{
    if (_matchFriendList == nil) {
        _matchFriendList = [[NSMutableArray alloc] init];
    }
    return _matchFriendList;
}
-(NSMutableArray *)keysArray{
    if (_keysArray == nil) {
        _keysArray = [[NSMutableArray alloc] init];
    }
    return _keysArray;
}
-(NSMutableArray *)modelArra{
    if (_modelArra == nil) {
        _modelArra = [[NSMutableArray alloc] init];
    }
    return _modelArra;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
